package org.jks.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.jks.constant.SysConfig;
import org.jks.constant.Constants;
import org.jks.model.AssessAttachment;
import org.jks.model.AssessSetting;
import org.jks.model.Attachment;
import org.jks.model.AttachmentType;
import org.jks.model.User;
import org.jks.request.model.UIAssess;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UITable;
import org.jks.service.AssessAttachmentService;
import org.jks.service.AssessSettingService;
import org.jks.service.AttachmentService;
import org.jks.service.AttachmentTypeService;
import org.jks.util.FileUtil;
import org.jks.util.JsonUtil;
import org.jks.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/assess")
public class AssessController {
	@Autowired
	AssessSettingService assessSettingService;
	@Autowired
	AssessAttachmentService assessAttachmentService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	AttachmentTypeService attachmentTypeService;
	
	@RequestMapping("/getAssessSetting")
	public void getAssessSetting(HttpServletRequest request, HttpServletResponse response)
	{
		ActionResult ar = new ActionResult();
		
		try{
			AssessSetting assessSetting = assessSettingService.first();
			if(assessSetting != null){
				ar.setSuccess(true);
				ar.setData(assessSetting);
			}
		}
		catch(Exception e)
		{
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/updateAssessSetting")
	public void updateAssessSetting(AssessSetting assess, HttpServletRequest request, HttpServletResponse response)
	{
		ActionResult ar = new ActionResult();
		try{
			assessSettingService.update(assess);
			ar.setSuccess(true);
		}
		catch(Exception e)
		{
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
		
	}
	
	/***
	 * 检查文件是否存在，如果存在将覆盖。
	 * @param file
	 * @param type
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/importAttachment")
	public void importAttachment(@RequestParam(value = "file") MultipartFile file, @RequestParam int type, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		ActionResult ar = new ActionResult();

		try{
			User user = (User)session.getAttribute(Constants.SESSION_ACCOUNT);
			String fileName = file.getOriginalFilename();
			
			if(attachmentService.isExist(user.getName() + "_" + fileName))
			{
				ar.setMsg("文件已存在，请重新选择！");
				ar.setSuccess(false);
			}
			else{
				AssessAttachment a = new AssessAttachment();
				
				a.setUser(user);
				
				Attachment w = new Attachment();
				w.setAddTime(new Date());
				w.setName(user.getName() + "_" + fileName);
				w.setPath(user.getName() + "_" + fileName);
				AttachmentType at = new AttachmentType();
				at.setId(type);
				w.setType(at);
				attachmentService.save(w);
				
				a.setAttachment(w);
				assessAttachmentService.save(a);				
				
				String folder = request.getServletContext().getRealPath("/") + File.separatorChar + SysConfig.ASSESS;
				File temp = new File(folder);
				if(!temp.exists()){
					temp.mkdir();
				}
				
				String filename = folder + File.separatorChar +  user.getName() + "_";
				
				FileUtil.uploadFile(request.getServletContext(), file, filename);
				ar.setSuccess(true);
			}
		}
		catch(Exception e)
		{
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("getAssessAttachment")
	public void getAssessAttachment(HttpServletRequest request, HttpServletResponse response, HttpSession session)
	{
		ActionResult ar = new ActionResult();

		try
		{		
			User user = (User)session.getAttribute(Constants.SESSION_ACCOUNT);
			List<AssessAttachment> temp = assessAttachmentService.findAllByUserId(user);
			UITable table = new UITable();
			table.setRows(temp);
			ar.setData(table);			
			ar.setSuccess(true);
		}
		catch(Exception e)
		{
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}		
		
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("deleteAssessAttachment/{id}")
	public void deleteAssessAttachment(@PathVariable long id,HttpServletRequest request, HttpServletResponse response, HttpSession session)
	{
		ActionResult ar = new ActionResult();

		try
		{		
			assessAttachmentService.delete(id);		
			ar.setSuccess(true);
		}
		catch(Exception e)
		{
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}		
		
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("getAssessList")
	public void getAssessList(int type, String startTime, String endTime,HttpServletRequest request, HttpServletResponse response,
			HttpSession session)
	{
		ActionResult ar = new ActionResult();
		
		try
		{			
			List<UIAssess> temp = getAssessAttachment(type, startTime, endTime);
			UITable table = new UITable();
			table.setRows(temp);
			ar.setData(table);			
			ar.setSuccess(true);
		}
		catch(Exception e)
		{
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}		
		
		ResponseUtil.returnJson(response, ar);
	}
	
	private int getScore(int type)
	{
		AssessSetting setting = assessSettingService.all().get(0);
		int score = 1;
				
		switch (type) {
			case 1:
				score = setting.getWeeklyWork();
				break;
			case 2:
				score = setting.getPartyOrganization();
				break;
			case 3:
				score = setting.getWeeklyEquipment();
				break;
			case 4:
				score = setting.getWorkReport();
				break;
			case 5:
				score = setting.getSafetyLearn();
				break;
			case 6:
				score = setting.getTechnicalReport();
				break;
			default:
				break;
		}
		
		return score;
	}
	
	@RequestMapping("/detail/{id}/{type}/{startTime}/{endTime}")
	public ModelAndView jixiao_detail(@PathVariable long id,
			@PathVariable int type,
			@PathVariable String startTime,
			@PathVariable String endTime,
			HttpServletRequest request, 
			HttpServletResponse response, 
			HttpSession session, 
			Map<String,Object> model) 
	{
		try 
		{
			List<AssessAttachment> tempList = assessAttachmentService.findAllByTime(startTime, endTime);
			if(tempList != null && tempList.size() != 0)
			{
				AssessSetting setting = new AssessSetting();
				
				for(AssessAttachment attachment : tempList)
				{
					if(attachment.getUser().getId() == id)
					{
						if(attachment.getAttachment().getType().getId() == 1)
						{
							setting.setWeeklyWork(setting.getWeeklyWork()+1);
						}
						if(attachment.getAttachment().getType().getId() == 2)
						{
							setting.setPartyOrganization(setting.getPartyOrganization() + 1);							
						}
						if(attachment.getAttachment().getType().getId() == 3)
						{
							setting.setWeeklyEquipment(setting.getWeeklyEquipment() + 1);							
						}
						if(attachment.getAttachment().getType().getId() == 4)
						{
							setting.setWorkReport(setting.getWorkReport() + 1);							
						}
						if(attachment.getAttachment().getType().getId() == 5)
						{
							setting.setSafetyLearn(setting.getSafetyLearn() + 1);							
						}
						if(attachment.getAttachment().getType().getId() == 6)
						{
							setting.setTechnicalReport(setting.getTechnicalReport() + 1);
						}
					}
				}
				model.put("assessAttachment", JsonUtil.Object2Json(setting));
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		org.jks.config.Config.init(request, response, session, model);
		return new ModelAndView("sysMgr/jixiao_detail", model);
	}
	
	private List<UIAssess> getAssessAttachment(int type, String startTime, String endTime)
	{
		List<AssessAttachment> temp = assessAttachmentService.findAllByTime(startTime, endTime);
		if(temp != null && temp.size() != 0)
		{
			HashMap<User, List<AssessAttachment>> sort = new HashMap<User, List<AssessAttachment>>();
			
			for(AssessAttachment attachment : temp)
			{
				if(sort.get(attachment.getUser()) == null)
				{
					List<AssessAttachment> t = new ArrayList<AssessAttachment>();
					t.add(attachment);
					sort.put(attachment.getUser(), t);
				}
				else 
				{
					List<AssessAttachment> t = sort.get(attachment.getUser());
					t.add(attachment);
				}
			}
			
			List<UIAssess> uiAssessList = new ArrayList<UIAssess>();		
			
			Iterator<Entry<User, List<AssessAttachment>>> it = sort.entrySet().iterator();
			while(it.hasNext()){
				@SuppressWarnings("rawtypes")
				Entry entry = (java.util.Map.Entry)it.next();
				UIAssess uia = new UIAssess();
				uia.setUser((User)entry.getKey());
				@SuppressWarnings("unchecked")
				List<AssessAttachment> tt  = (List<AssessAttachment>)entry.getValue();
				uia.setAssessAttachment(tt);
				
				int score = 100;
				for(AssessAttachment assessAttachment : tt)
				{
					score += getScore((int)assessAttachment.getAttachment().getType().getId());
				}
				uia.setScore(score);
				if(type == 1)
				{
					uia.setType("年度考核");
				}
				else
				{
					uia.setType("月度考核");
				}
				uiAssessList.add(uia);
			} 
			
			return uiAssessList;
		}
		
		return null;			
	}
	
	
	@RequestMapping("/export/{type}/{startTime}/{endTime}")
	public void export(@PathVariable int type,
			@PathVariable String startTime,
			@PathVariable String endTime,
			HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<String,Object> model) throws RowsExceededException, WriteException, IOException 
	{
		
		List<UIAssess> temp = getAssessAttachment(type, startTime, endTime);
		
		response.setContentType("applicationnd.ms-excel");    
		response.setHeader("Content-Disposition", "attachment;filename=" + "yeji.xls"); 
		ServletOutputStream sos = response.getOutputStream();
		WritableWorkbook workbook = Workbook.createWorkbook(sos);
		WritableSheet sheet = workbook.createSheet("sheet1", 0);
		
		sheet.setColumnView(0, 30);
		sheet.setColumnView(1, 30);
		sheet.setColumnView(2, 30);
		sheet.setColumnView(3, 30);
		sheet.setColumnView(4, 30);
		sheet.setColumnView(5, 30);
		sheet.mergeCells(0, 0, 5, 0);
		WritableFont wf = new WritableFont(WritableFont.TIMES, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
		WritableCellFormat wcf = new WritableCellFormat(wf);
		wcf.setAlignment(Alignment.CENTRE);
		wcf.setBackground(Colour.GRAY_50);
		Label lab = null;
		lab = new Label(0, 0, "本次导出业绩考核", wcf);
		
		sheet.addCell(lab);
		
		WritableFont wf1 = new WritableFont(WritableFont.TIMES, 12,
				WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
				Colour.BLACK);
		WritableCellFormat wcf1 = new WritableCellFormat(wf1);
		wcf1.setBackground(Colour.GRAY_25);
		lab = new Label(0, 1, "", wcf1);
		sheet.addCell(lab);
		lab = new Label(1, 1, "姓名", wcf1);
		sheet.addCell(lab);
		lab = new Label(2, 1, "考核类型", wcf1);
		sheet.addCell(lab);
		lab = new Label(3, 1, "考核成绩", wcf1);
		sheet.addCell(lab);
		lab = new Label(4, 1, "所属部门", wcf1);
		sheet.addCell(lab);
		lab = new Label(5, 1, "所属班组", wcf1);
		sheet.addCell(lab);
		
		int index = 2;
		if(temp != null)
		{
			for(int i = 0; i < temp.size(); i++)
			{
				UIAssess assess = temp.get(i);
				lab = new Label(0, index, i + "");
				sheet.addCell(lab);
				lab = new Label(1, index, assess.getUser().getName());
				sheet.addCell(lab);
				lab = new Label(2, index, assess.getType());
				sheet.addCell(lab);
				lab = new Label(3, index, assess.getScore() + "");
				sheet.addCell(lab);
				if(assess.getUser().getDepartment() == null)
				{
					lab = new Label(4, index, "");
				}
				else
				{
					lab = new Label(4, index, assess.getUser().getDepartment().getName());
				}
				sheet.addCell(lab);
				if(assess.getUser().getFlight() == null)
				{
					lab = new Label(5, index, "");
				}
				else 
				{
					lab = new Label(5, index, assess.getUser().getFlight().getName());
				}
				
				sheet.addCell(lab);
				index++;
			}
		}
		
		
		workbook.write();
		workbook.close();
	}
	
	@RequestMapping("/download/{id}")
	public void download(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response){
		Attachment ass = attachmentService.findById(id);
		
		String folder = request.getServletContext().getRealPath("/") + File.separatorChar + SysConfig.ASSESS;
		File temp = new File(folder);
		if(!temp.exists()){
			temp.mkdir();
		}
		
		String filePath = folder + File.separatorChar +  ass.getName();
		
		FileUtil.download(filePath,  ass.getName(), response);
	}
}
